import React, { memo } from 'react';
import _ from 'lodash';
import { Tabs } from 'antd';
import { useEditor } from '@craftjs/core';
import { combination, atomic, layout } from '@/components/PageDesignerComponents';
import { getComponentDisplayName } from '@/utils/utils';
import styles from './index.less';

const renderComponent = ({ list, create, closeDrawerOnce }) =>
  list.map(({ previewImg, displayName, component }, index) => (
    <div
      key={`${displayName}-${index}`}
      title={displayName}
      className={styles.componentDragListItem}
      style={index > 2 ? { borderTopColor: 'transparent' } : {}}
      ref={(ref) => create(ref, React.createElement(component))}
      onDrag={() => {
        closeDrawerOnce();
      }}
    >
      <div className={styles.componentDragListItemImgCube}>
        <img
          src={previewImg}
          alt={displayName || getComponentDisplayName(component)}
          className={styles.componentDragListItemImgItem}
        />
      </div>
      <div className={styles.componentDragListItemText}>{displayName}</div>
    </div>
  ));

export default memo(({ closeDrawer }) => {
  const {
    connectors: { create },
  } = useEditor();

  const closeDrawerOnce = _.once(closeDrawer);

  return (
    <div className={styles.tabContainer}>
      <Tabs defaultActiveKey="combinationComponent">
        <Tabs.TabPane key="combinationComponent" tab="复合组件">
          <div className={styles.componentDragListContainer}>
            {renderComponent({ list: combination, create, closeDrawerOnce })}
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="atomicComponent" tab="原子组件">
          <div className={styles.componentDragListContainer}>
            {renderComponent({ list: atomic, create, closeDrawerOnce })}
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="layoutComponent" tab="布局组件">
          <div className={styles.componentDragListContainer}>
            {renderComponent({ list: layout, create, closeDrawerOnce })}
          </div>
        </Tabs.TabPane>
      </Tabs>
    </div>
  );
});
